package com.hisense.ovcloud.common3.webclient;

import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import static io.netty.channel.ChannelOption.*;

@Configuration
public class WebConfig implements WebFluxConfigurer {
    public final WebClientProperties properties;

    @Value("${server.readerIdleTimeSeconds:3600000}")
    private int readerIdleTimeSeconds;
    @Value("${server.writerIdleTimeSeconds:3600000}")
    private int writerIdleTimeSeconds;
    @Value("${server.allIdleTimeSeconds:3600000}")
    private int allIdleTimeSeconds;
    @Value("${server.autoClose:false}")
    private boolean autoClose;

    public WebConfig(WebClientProperties properties) {
        this.properties = properties;
    }

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.defaultCodecs().maxInMemorySize(properties.getMaxInMemorySize());
    }

    @Bean
    public ReactiveWebServerFactory reactiveWebServerFactory() {
        NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory();
        factory.addServerCustomizers(builder -> builder
                .doOnConnection(conn -> {
                    conn.channel().config().setOption(SO_KEEPALIVE, true);
                    conn.channel().config().setOption(SO_TIMEOUT, allIdleTimeSeconds);
                    conn.channel().config().setOption(AUTO_CLOSE, autoClose);
                    conn.addHandlerLast(new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
                }));

        return factory;
    }
}
